import * as $user from '@/api/user'
import {PROGRESS_SET_PROGRESSES, PROGRESS_RESET_PROGRESSES} from './progress'
import {UI_SET_PAGE} from './ui'

export const USER_SET_ROLE = 'USER_SET_ROLE'
export const USER_UPDATE_USER_AVATAR_URL = 'USER_UPDATE_USER_AVATAR_URL'
export const USER_UPDATE_USER_NAME = 'USER_UPDATE_USER_NAME'
export const USER_SET_GROUPS = 'USER_SET_GROUPS'
export const USER_SET_GROUP = 'USER_SET_GROUP'

const state = () => {
  let role = wx.getStorageSync('role') || ''
  return {
    role,
    user: {
      id: 0,
      nickName: '',
      avatarUrl: ''
    },
    groups: [],
    group: {
      id: 0,
      name: '',
      avatarUrl: '',
      openGroupId: '',
      createdAt: '',
      users: [],
      members: []
    },
  }
}

const getters = {
  role: state => state.role,
  groups: state => state.groups,
  group: state => state.group,
  roleName (state) {
    if (state.role === 'teacher') return '老师'
    if (state.role === 'student') return '学生'
    return ''
  }
}

const actions = {
  async getProgressesByPage ({ commit, state, rootState }, { pi }) {
    if (pi === 0) {
      commit('progress/' + PROGRESS_RESET_PROGRESSES, [], {root: true})
    }
    let page = await $user.getProgressesByPage({pageIndex: pi})
    commit('progress/' + PROGRESS_SET_PROGRESSES, page.rows, {root: true})
    let {totalCount, hasMore, totalPages, pageSize, pageIndex} = page
    commit(UI_SET_PAGE, {totalCount, hasMore, totalPages, pageIndex, pageSize}, {root: true})
  },
  async getGroups ({ commit, state, rootState }) {
    let groups = await $user.getGroups()
    commit(USER_SET_GROUPS, groups)
  },
  async getGroupById ({ commit, state, rootState }, {groupId, cache = true}) {
    let group = await $user.getGroupById({groupId, cache})
    commit(USER_SET_GROUP, group)
  },
  setRole ({ commit, state }, role) {
    commit(USER_SET_ROLE, role)
    wx.setStorageSync('role', role)
  },
}

const mutations = {
  USER_SET_ROLE (state, role) {
    state.role = role
  },
  USER_SET_GROUPS (state, groups) {
    state.groups = groups
  },
  USER_SET_GROUP (state, group) {
    state.group = group
  },
}

export default {
  state,
  getters,
  actions,
  mutations
}
